import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators, AbstractControl } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';

// services
import { ConstantService } from '../../../../../core/services/constant.service';
import { ServerService } from '../../../../../core/services/server.service';
import { StorageService } from '../../../../../core/services/storage.service';

// plugins
import _ from 'lodash';

@Component({
    selector: 'app-school-management',
    templateUrl: './school-management.component.html',
    styleUrls: ['./school-management.component.css']
})
export class SchoolManagementComponent implements OnInit {
    schoolForm: FormGroup; // 学校管理表单
    isVisible: boolean = false; // 是否显示modal
    isConfirmLoading: boolean = false; // modal中点击保存的时候的过渡效果
    isViewStateUpdate: boolean = false;  // 页面是否是更新状态
    provinces: object[] = []; // 省市区信息
    schoolList: object[] = []; // 全部学校列表
    _current: number = 1;
    _pageSize: number = 10;
    _total: number = 1;
    _loading: boolean = true;
    cityArray: object[] = []; // 市
    areaArray: object[] = []; // 区

    constructor(
        private fb: FormBuilder,
        private constant: ConstantService,
        private server: ServerService,
        private storage: StorageService,
        private message: NzMessageService
    ) {
        /**
         * 初始化学校管理表单
         * username: 用于生成学校管理员用户
         * schoolName: 学校名称
         * schoolmaster: 学校负责人
         * province: 省份 城市 地区
         * address: 地址
         * introduction: 介绍
         * count: 数量 teacher: 教师数量; student: 学生数量
         */
        this.schoolForm = this.fb.group({
            _id: [''],
            username: [null, [Validators.required, Validators.minLength(6)]],
            schoolName: [null, Validators.required],
            schoolmaster: [null, Validators.required],
            province: [[], Validators.required],
            address: [null, Validators.required],
            introduction: [null],
            teacherCount: [null],
            studentCount: [null]
        });
    }

    ngOnInit() {
        this.getProvince();
        // 获取全部学校
        this.getAllSchools();
        // 将结构型省市区数据拆解成单层省、市、区数据
        // 三次循环获取
        for (let c of this.provinces) {
            if (c['children']) {
                this.cityArray = this.cityArray.concat(c['children']);
            }
        }
        for (let a of this.cityArray) {
            if (a['children']) {
                this.areaArray = this.areaArray.concat(a['children']);
            }
        }
    }

    /**
     * 显示modal,添加或更新学校信息
     * @param id 
     */
    async showModal(id) {
        this.isVisible = true;
        if (this.provinces) {
            if (id) {
                this.isViewStateUpdate = true;
                const result = await this.server.fetch(this.constant.api.manage.school.findOne, { id });
                if (result) {
                    this.schoolForm.controls['_id'].setValue(result.data._id);
                    this.schoolForm.controls['username'].setValue(result.data.username);
                    this.schoolForm.controls['schoolName'].setValue(result.data.schoolName);
                    this.schoolForm.controls['schoolmaster'].setValue(result.data.schoolmaster);
                    this.schoolForm.controls['province'].setValue([
                        { value: result.data.province, label: this.findProvinceOrCityName(result.data.province) },
                        { value: result.data.city, label: this.findProvinceOrCityName(result.data.city) },
                        { value: result.data.area, label: this.findProvinceOrCityName(result.data.area) }
                    ]);
                    this.schoolForm.controls['address'].setValue(result.data.address);
                    this.schoolForm.controls['introduction'].setValue(result.data.introduction);
                    this.schoolForm.controls['teacherCount'].setValue(result.data.count.teacher);
                    this.schoolForm.controls['studentCount'].setValue(result.data.count.student);
                }
            } else {
                this.isViewStateUpdate = false;
                this.schoolForm.reset();
            }
        } else {
            this.message.error('抱歉,获取省市区信息失败,请联系系统管理员');
        }
    }

    // 获取表单项
    getFormControl(name): AbstractControl {
        return this.schoolForm.controls[name];
    }

    /**
     * 保存 || 更新
     * @param e 
     * @param school 
     */
    async handleOk(e, school): Promise<void> {
        this.isConfirmLoading = true;
        console.log(school);
        if (typeof school.province[0] === 'object') {
            school.province = _.map(school.province, p => p.value);
        }
        // 保存
        const result = await this.server.fetch(this.constant.api.manage.school[this.isViewStateUpdate ? 'update' : 'save'], school);
        if (result) {
            this.message.success('保存学校成功');
            if (!this.isViewStateUpdate) {
                // 清空表单
                this.schoolForm.reset();
            } else {
                this.isVisible = false;
            }
            this.isConfirmLoading = false;
            this.getAllSchools();
            this.isVisible = false;
        } else {
            this.isConfirmLoading = false;
        }

    }

    /**
     * 关闭modal
     * @param e 
     */
    handleCancel(e): void {
        this.isVisible = false;
    }

    /**
     * 获取全部学校列表
     */
    async getAllSchools(): Promise<void> {
        const param = {
            page: this._current,
            limit: this._pageSize
        };
        const allSchools = await this.server.fetch(this.constant.api.manage.school.findAll, param);
        if (allSchools) {
            for (let school of allSchools.data.data) {
                school.province = this.findProvinceOrCityName(school.province);
                school.city = this.findProvinceOrCityName(school.city);
                school.area = this.findProvinceOrCityName(school.area);
            }
            this.schoolList = allSchools.data.data;
            this._total = allSchools.data.count;
            this._loading = false;
        }
    }

    /**
     * 删除学校
     * @param id 
     */
    async del(id: string): Promise<void> {
        const result = await this.server.fetch(this.constant.api.manage.school.del, { id });
        if (result) {
            this.message.success('删除成功');
            this.getAllSchools();
        }
    }

    /**
     * 禁用学校
     * @param id 
     */
    async disable(id: string, status: number): Promise<void> {
        const result = await this.server.fetch(this.constant.api.manage.school.disable, { id, status });
        if (result) {
            this.message.success(status === 1 ? '启用成功' : '禁用成功');
            this.getAllSchools();
        }
    }

    /**
     * 获取省市区信息
     */
    async getProvince(): Promise<void> {
        let provinces = this.storage.getItem('province_city_area');
        if (!provinces) {
            const result = await this.server.fetch(this.constant.api.common.province, {});
            this.provinces = result.data;
            // 缓存
            this.storage.setItem('province_city_area', result.data);
        } else {
            this.provinces = provinces;
        }
    }

    /**
     * 根据value查找省市区名称
     * @param value 
     */
    findProvinceOrCityName(value: string): string {
        let province = this.provinces.filter(p => p['value'] === Number(value));
        if (province.length === 0) {
            let city = this.cityArray.filter(c => c['value'] === Number(value));
            if (city.length === 0) {
                let area = this.areaArray.filter(a => a['value'] === Number(value));
                if (area.length === 0) {
                    return '';
                } else {
                    return area[0]['label'];
                }
            } else {
                return city[0]['label'];
            }
        } else {
            return province[0]['label'];
        }
    }
}
